<template>
  <div class="w-full">
    <app-header />

    <van-tabs color="#e68531" v-model:active="activeID" @click-tab="onClickTab">
      <van-tab :title="item.name" :name="item.id" v-for="item in channels"></van-tab>
    </van-tabs>
    
    <van-list
      v-model:loading="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
    >
      <div class="w-full p-3 flex flex-wrap flex-row gap-3">
        <div class="w-[calc(50%-8px)]" v-for="(item, index) in list" :key="index">
          <nuxt-link :to="`/video/${item.id}`">
            <div class="img relative">
              <img :src="item.coverUrl" class="w-full h-[150px] object-cover" alt="">
              <div class="bg-black/50 absolute bottom-0 left-0 w-full p-2 flex items-center justify-between">
                <p class="text-white text-xs">{{ item.views }}</p>
                <p class="text-white text-xs">{{ item.likes }}</p>
              </div>
            </div>
            <div class="p-2 pb-0">
              <p class="text-sm line-clamp-2">{{ item.title }}</p>
              <p class="text-xs text-gray-500 mt-1">{{ item.uploadDate }}</p>
            </div>
          </nuxt-link>
        </div>
      </div>
    </van-list>

    <app-footer />
  </div>
</template>

<script setup lang="ts">
import type { VideoObject } from '@/types/video'

// 设置SEO关键字
useSeoMeta({
  title: '小花奢侈品  一站式奢侈品交易平台',
  description: '小花不只是一家中古店，更是「一站式」正品奢侈品交易平台，全国较早的二手奢侈品仓库。在绿色可循环理念的加持下，将回收、置换、寄卖、鉴别、养护这五大服务不断完善，为每一位向往美好的人提供全面、专业、信赖、专属的一站式服务。'
})

// TAB 响应
const activeID = ref<number | null>(null)
const videos = ref<VideoObject[]>([])

const loading = ref(false)
const finished = ref(false)
const page = ref(1)
const pageSize = ref(8)
const list = ref<VideoObject[]>([])

// 获取channels数据
const { data: channels } = await useFetch('/api/channelList')

// 加载视频列表数据
const loadVideos = async (channelId: number) => {
  const { data } = await useFetch(`/api/videoList?channelId=${channelId}`)
  videos.value = data.value as VideoObject[]
  onLoad()
}

// 初始加载第一个频道数据
watch(channels, (newChannels) => {
  if(newChannels?.length && activeID.value === null) {
    activeID.value = newChannels[0]?.id as number
    loadVideos(newChannels[0]?.id as number)
  }
}, { immediate: true })

// 点击tab - 调用接口
const onClickTab = async ({ name }: { name: number }) => {
  activeID.value = name

  // 重置分页状态
  page.value = 1
  list.value = []
  finished.value = false

  loadVideos(activeID.value)
}

const onLoad = () => {
  console.log('触底加载');
  // 加载状态开始
  loading.value = true;

  let curList = videos.value?.slice((page.value - 1) * pageSize.value, page.value * pageSize.value) as VideoObject[]
  if (curList?.length) {
    list.value.push(...curList)
    page.value++
  }

  // 加载状态结束
  loading.value = false

  // 数据全部加载完成
  if(list.value?.length === videos.value?.length) {
    finished.value = true
  }
}
</script>
